import React, { useState, useEffect } from "react";
import { NavBar, Avatar, List, Input, Button, Space, Dialog, Empty } from 'antd-mobile';
import { getPersonChatList, createChat } from '@/service/chat';
import { AddOutline } from 'antd-mobile-icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import styles from './index.module.less';
import ModelSelector from '@/components/ModelSelector';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';

const PersonasList = () => {
  const [personas, setPersonas] = useState([]);
  const navigate = useNavigate();
  const [params] = useSearchParams();
  const customNavigate = $globalNavigate()
  const role_id = params.get('role_id');
  const type = params.get('type');
  const [modelVisible, setModelVisible] = useState(false);
  const [currentModelId, setCurrentModelId] = useState('');
  const [currentChatId, setCurrentChatId] = useState('');
  
  console.log("🚀 ~ role_id:", role_id)
  useEffect(() => {
    getPersonChatList().then(res => {
      setPersonas(res);
    });
  }, []);
  
  const handleModelChange = (modelId) => {
    setCurrentModelId(modelId);
    // 模型选择成功后导航到聊天页面
    if (currentChatId) {
      showSuccessToast('模型设置成功');
      navigate(`/chatDetail?chatId=${currentChatId}&type=chat`);
    }
  };
  
  const handleSelectPersona = (id) => {
    const submitChatData = {
      role_id: role_id,
      personas_id: id
    }
    Dialog.confirm({
      content: ' 是否使用此角色开始故事（选择后无法更换）？',
      onConfirm: () => {
        createChat(submitChatData).then(res => {
          console.log("🚀 ~ handleSelectPersona ~ res:", res)
          if (res.chat_id) {
            setCurrentChatId(res.chat_id);
            // 打开模型选择弹窗
            setModelVisible(true);
          } else {
            showErrorToast('创建聊天失败，请重试');
          }
        }).catch(error => {
          showErrorToast('创建聊天失败，请重试');
        });
      }
    })
  }
  
  const handleAddPersona = () => {
    navigate(`/personas/add?role_id=${role_id}`)
  }
  
  const right = <div style={{ fontSize: 24 }} onClick={handleAddPersona}><AddOutline /></div>
  
  const back = () => {
    customNavigate(`/world`)
  }
  return <div className={styles.PersonasListWrapper}>
    <NavBar right={right} onBack={back}>
      选择聊天角色
    </NavBar>
    <div className={styles.PersonasListContainer}>
      <List>
        {personas.map(user => (
          <List.Item
            key={user.id}
            className={styles.listItem}
            onClick={() => handleSelectPersona(user.id)}
            prefix={
              <Avatar
                src={user.cover}
                style={{ borderRadius: 20 }}
                fit='cover'
                width={40}
                height={40}
              />
            }
            description={user.persona_name}
          >
          </List.Item>
        ))}
      </List>
      {personas.length === 0 && <Empty description='暂无角色，请点击右上角添加角色' />}
      <div className={styles.footer}>
        请选择或创建你的角色来开始故事
      </div>
    </div>
    
    {/* 模型选择弹窗 */}
    <ModelSelector
      visible={modelVisible}
      onClose={() =>  {
        setModelVisible(false)
        navigate(`/chatDetail?chatId=${currentChatId}&type=chat`);
      }}
      modelId={currentModelId}
      onModelChange={handleModelChange}
      chatId={currentChatId}
      type={type}
    />
  </div>;
};

export default PersonasList;
